import CryptoJS from "crypto-js";

function convertToHexSecretKey(host) {
  const hash = CryptoJS.SHA256(host);
  return hash.toString(CryptoJS.enc.Hex);
}
let defaultHost = import.meta.env.VITE_BASE_HOST;
const SECRET_KEY = convertToHexSecretKey(defaultHost);
export const encryptedStorage = {
  setItem(key, value) {
    const encryptedValue = CryptoJS.AES.encrypt(
      JSON.stringify(value),
      SECRET_KEY
    ).toString();
    localStorage.setItem(key, encryptedValue);
  },
  getItem(key) {
    const encryptedValue = localStorage.getItem(key);
    if (encryptedValue) {
      const bytes = CryptoJS.AES.decrypt(encryptedValue, SECRET_KEY);
      return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
    }
    return null;
  },
  removeItem(key) {
    localStorage.removeItem(key);
  },
};
